<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkContact\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\WorkContact\Action\Dashboard\Traits\ContactStageUpdateTrait;
use MoChat\App\WorkContact\Event\AddContactEvent;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\WeWork\WeWork;
use Psr\Container\ContainerInterface;

/**
 * 添加用户监听，触发阶段更改.
 *
 * @Listener(priority=9999)
 */
class UpdateContactStageListener implements ListenerInterface
{
    use ContactStageUpdateTrait;

    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var WeWork
     */
    protected $client;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function listen(): array
    {
        return [
            AddContactEvent::class,
        ];
    }

    public function process(object $event)
    {
        $message = $event->message;

        Db::beginTransaction();
        try {
            // 阶段自动化
            $this->contactStageUpdate($message['id'], $message['employeeId'], $message['corpId']);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }
}
